package com.billing.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 名片识别api
 * @author pc
 *
 */
public class CardApiUtil {
	public static Map<String, Object> getCardImageData(String filepath){
		//请求地址
        String url="http://netocr.com/api/recogliu.do";
        //用户ocrKey
        String key = "JVD7TnD9qudFpUH5ADhip6";
        //用户ocrSecret
        String secret = "ed586a6aea3a4c10a8dcd9f62f760b02";
        //请求参数
        Map params = new HashMap();
        Map<String, Object> returnmap = new HashMap<>();
        params.put("img",Base64Util.GetImageStr(filepath));
        params.put("key",key);
        params.put("secret",secret);
        params.put("typeId",20);
        params.put("format","json");
        String result = doPost(url, urlencode(params));
        System.out.println(result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject jsonObject2 = (JSONObject) jsonObject.getJSONArray("cardsinfo").get(0);
        int code = (Integer) jsonObject.getJSONObject("message").getInt("status");
        if(code != 0){
        	returnmap.put("code", -1);
        	return returnmap;
        }
        JSONArray jsonArray = jsonObject2.getJSONArray("items");
        for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject3 = jsonArray.getJSONObject(i);
			if(jsonObject3.get("desc").equals("姓名")){
				returnmap.put("lkmName", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("职务/部门")) {
				returnmap.put("lkmPostion", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("手机")) {
				returnmap.put("lkmMobile", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("公司") && ((String)jsonObject3.get("content")).indexOf("公司") != -1) {
				returnmap.put("custName", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("地址")) {
				returnmap.put("custAddress", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("电话")) {
				returnmap.put("lkmTel", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("电子邮箱")) {
				returnmap.put("lkmEmail", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("网址")) {
				returnmap.put("custWebsite", jsonObject3.get("content"));
			}else if (jsonObject3.get("desc").equals("邮编")) {
				returnmap.put("custZip", jsonObject3.get("content"));
			}
		}
        returnmap.put("code", 0);
        return returnmap;
	}
	
	/**
     * HTTP的Post请求方式
     * @param strUrl 访问地址
     * @param param 参数字符串
     * */
    public static String doPost(String strUrl, String param) {
        String returnStr = null; // 返回结果定义
        URL url = null;
        HttpURLConnection httpURLConnection = null;
  
        try {
            url = new URL(strUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST"); // post方式
            httpURLConnection.connect();
            //System.out.println("ResponseCode:" + httpURLConnection.getResponseCode());
            //POST方法时使用
            byte[] byteParam = param.getBytes("UTF-8");
            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
            out.write(byteParam);
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
  
            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }
 
     
    //将map型转为请求参数型
    public static String urlencode(Map<String, Object> data) {
        StringBuilder apistore = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                apistore.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return apistore.toString();
    }
     
    // 发起请求,获取内容
    public static void main(String[] args) {
       CardApiUtil.getCardImageData("D:\\tess4j\\image\\412153541.jpg");
    }
}
